#!/usr/bin/python
# -*- coding: utf-8 -*-

"""Project Euler Solution 072

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import cProfile
from euler.numbers.advanced_math import totients

def get_answer():
    """Question:
    
    Consider the fraction, n/d, where n and d are positive integers. If n<d and 
    HCF(n,d)=1, it is called a reduced proper fraction.

    If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, 
    we get:
    
    1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 
    4/5, 5/6, 6/7, 7/8
    
    It can be seen that there are 21 elements in this set.
    
    How many elements would be contained in the set of reduced proper fractions 
    for d ≤ 1,000,000?
    """
    
    #A reduced proper fraction n/d requires than n be less than d and coprime to d. 
    #Therefore in order to solve this problem, we need to add up the number of coprimes
    #of d which are < d for all d <= 1,000,000. The φ function can be used to 
    #calculate the number of coprimes of d which area < d. Therefore, this problem can 
    #be solved by summing the results of φ(n) for all n <= 1,000,000.
    return sum(totients(1000000))

if __name__ == "__main__":
    cProfile.run("print(get_answer())")
